<template>
  <div class="scrollbox">
    <v-header goback="1"></v-header>
    <div class="dis30"></div>
    <div class="aps8">
      <div class="uploadbox">
        <form method="post" enctype="multipart/form-data" action="#">
          <el-button size="small" :type="token ? 'primary': 'default'" :disabled="token == ''"><i class="f16 el-icon-video-camera"></i> 请选择待上传视频</el-button>
          <input class="file-input" multiple="multiple" @change="selectFileHandle" type="file" v-show="token" :accept="video_types.join(',')"  />
          <el-button type="default" size="small"  @click.stop="stopUpload(-1)" v-show="0">停止上传</el-button>
        </form>
      </div>
    </div>
    <div class="dis15"></div>
    <div class="cards aps8" style="min-height: 300px;">
      <div class="filelist-box" v-if="fileList.length > 0">
        <div class="filelist-item" v-for="(item, index) in fileList" :key="index">
          <!--loading bar -->
          <div class="item-cover" :style="'width:' + item.total.percent + '%'" v-if="item.total.percent < 100"></div>
          <!--loading bar end -->
          <div class="item-content">
            <div class="item-video" v-if="item.rid > 0" @mouseenter="mouseoverVideo(item)" @mouseleave="mouseoutVideo(item)">              
              <video height="130" :src="item.src" :poster="item.src + '?vframe/jpg/offset/1'" autoplay="autoplay" loop muted v-if="payrid == item.rid"></video>
              <img :src="item.src + '?vframe/jpg/offset/1'" height="130" v-else />
            </div>
            <div class="item-name">
              <i class="el-icon-video-camera f14 font-blue"></i> <span class="font-blue f14">{{ item.name }} </span> 
            </div>           
            <div class="item-btn">
              <template v-if="item.rid > 0">
                <el-button size="mini" type="danger" @click.stop="deleteResource(item, index)">删除</el-button>                
              </template>
              <template v-else>
                <el-button size="mini" @click.stop="stopUpload(index)" v-if="item.start">暂停</el-button>
                <el-button size="mini" type="primary" @click.stop="startUpload(index)" v-else>开始</el-button>
                <el-button size="mini" icon="el-icon-close" circle @click.stop="removeUpload(index)"></el-button>
              </template>
            </div>
            <div class="item-percent">
              <template v-if="item.rid > 0">
                <span class="font-green f12"><i class="el-icon-success"></i>上传成功!</span>              
              </template>
              <template v-else>
                <template v-if="item.start">
                  <span class="font-green">{{ item.total.percent }} %</span>
                  <span class="font-gray2 f9">({{ item.download_rate | formatSize }}/s)</span>
                </template>
                <template v-else>
                  <span class="font-gray2 f12">已暂停上传</span>
                </template>                               
              </template>              
            </div>
            <div class="item-size font-gray f12">
              {{ item.size | formatSize }}
            </div>
            
            <div>
            </div>
            <div class="cl"></div>
          </div>
        </div>
      </div>
      <div class="nodata tc font-gray2" v-else>
        <i class="el-icon-video-camera f20 font-gray2"></i> 请选择视频文件上传
      </div>
      <div class="dis60"></div>
    </div>
  </div>
</template>

<script>
import * as qiniu from 'qiniu-js'
import md5 from 'js-md5'
export default {
  props: ["id"],
  data() {
    return {
      fileList: [],
      token: '',
      path: '',
      config: {
        useCdnDomain: true,
        disableStatisticsReport: false,
        retryCount: 6,
        region: ''
      },
      putExtra: {
        fname: "",
        params: {},
        mimeType: null
      },
      video_types: [],
      payrid: 0
    }
  },
  mounted() {
    this.getToken()
    let video_types = this.$config('video_type')
    if (video_types) {
      for (let i in video_types) {
        this.video_types.push(video_types[i])
      }
    }
  },
  methods: {
    mouseoverVideo (item) {
      this.payrid = item.rid
    },
    mouseoutVideo (item) {
      this.payrid = 0
    },
    deleteResource (item, index) {
      let that = this
      that.$confirm('此操作会将该彻底删除，不可恢复, 是否继续?', '删除提醒').then(() => {
        let url = 'resources.del'
        that.$api.post(url, { rid: item.rid }).then((res) => {
          if (res.status === 1) {
            that.$success(res.msg)
            this.removeUpload(index)
          } else {
            that.$error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    removeUpload (index) {
      this.stopUpload(index)
      this.fileList.splice(index, 1)
    },
    startUpload (index) {
      let that = this
      if (index == -1) {
        that.fileList.forEach((f) => {
          that.subscribe(f)
        })
      } else {
        let f = that.fileList[index]
        that.subscribe(f)
      }
    },
    stopUpload (index) {
      let that = this
      if (index == -1) {
        that.fileList.forEach((f) => {
          that.unsubscribe(f)
        })
      } else {
        let f = that.fileList[index]
        that.unsubscribe(f)
      }
    },
    subscribe (f) {
      let that = this
      if (f.start == false) {
        f.start = true
        f.subscription = f.observable.subscribe({
          next (res) {
            let timestamp = new Date().getTime()
            if (!f.lasttotal.loaded) {
              f.download_rate = 0
              f.lasttotal.loaded = f.total.loaded
              f.lasttotal.timestamp = timestamp
            } else {
              if ((timestamp - f.lasttotal.timestamp) >= 1000) {
                f.download_rate = f.total.loaded - f.lasttotal.loaded
                f.download_rate = f.download_rate > 0 ? f.download_rate : 0
                f.lasttotal.loaded = f.total.loaded
                f.lasttotal.timestamp = timestamp
              }              
            }
            f.chunks = res.chunks||[]
            f.total = res.total
            f.total.percent = Math.round(f.total.percent, 1)
          },
          error (err) {
            that.$error('上传出错!')
          },
          complete (res) {
            f.src = res.path
            f.poster = res.poster
            f.rid = res.rid
          }
        })
      }
    },
    unsubscribe (f) {
      if (f.start) {
        f.start = false
        f.subscription.unsubscribe()
      }
    },
    selectFileHandle (e) {
      let o = e.target
      for (let i =0; i < o.files.length; i++) {
        let file = o.files[i]
        let ftype = file.type
        let fext = this.getExt(file.name)
        let fkey = this.path + md5(file.name) + '.' + fext
        if (this.fileList.find_key_val('fkey', fkey) === -1) {
          if (this.video_types.indexOf(ftype) >= 0) {              
            // this.putExtra.params["x:name"] = file.name.split(".")[0];
            this.putExtra.fname = file.name.split(".")[0];
            this.fileList.push({
              'rid': 0,
              'fkey': fkey,
              'name': file.name,
              'size': file.size,
              'src': '',
              'poster': '',
              'chunks': [],
              'total': {},
              'lasttotal': {},
              'download_rate': 0,
              'start': false,
              'observable': qiniu.upload(file, fkey, this.token, this.putExtra, this.config),
              'subscription': null
            })
          }
        }
      }
      o.value = ''
      this.startUpload(-1)
    },
    getExt (name) {
      return name.substr(name.lastIndexOf(".") + 1).toLowerCase()
    },
    getToken () {
      this.$api.get('qiniup.get_token').then((res) => {
        if (res.status == 1) {
          this.token = res.data.token
          this.config.region = res.data.region
          this.path = res.data.path
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.uploadbox { position:relative; }
.video-mini-box {min-height: 120px;background:#efefef;}
.video-mini-box i {font-size: 42px;}
.file-input {opacity:0; position:absolute;top:0;left:0;width:142px;height:38px;cursor:pointer;}

.filelist-box {}
.filelist-item {border-bottom:solid 1px #efefef;padding: 13px 0px;position:relative;}
.filelist-item .item-cover {position:absolute;width:100%;height:100%;background:#e2eeff;opacity:0.7;top:0px;left:0px;bottom:0px;z-index:1;}
.filelist-item .item-content {position:relative;z-index:2;}

.filelist-item .item-video {float:left; max-width:300px;height:130px;overflow:hidde;padding:0 12px;}
.filelist-item .item-name {
  float:left;
  padding-left: 12px;
  max-width:600px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.filelist-item .item-size {float:right;width:150px;}
.filelist-item .item-percent {float:right;width:170px;}
.filelist-item .item-btn {float:right;width:150px; text-align:right;padding-right:12px;}
.nodata {padding: 38px 0;text-align:center;}
</style>
